<script setup>
import { ref, defineProps, defineEmits, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {Upload} from "@element-plus/icons-vue";

const props = defineProps({
  messages: Array,
  connecting: Boolean
})
const emit = defineEmits(['send-message'])
const messageInput = ref('')
const uploadUrl = ref('/api/upload/image')

const handleSubmit = () => {
  if (messageInput.value.trim()) {
    emit('send-message', messageInput.value.trim(), 'CHAT')
    messageInput.value = ''
  }
}

// 图片上传处理
const handleUploadSuccess = (response) => {
  const imageUrl = `/uploads/${response}`
  emit('send-message', imageUrl, 'IMAGE')
}

const handleUploadError = () => {
  ElMessage.error('图片上传失败')
}

// 自动滚动逻辑
const scrollMenuRes = ref(null)
function scrollToBottom() {
  nextTick(() => {
    if (scrollMenuRes.value?.$el) {
      const container = scrollMenuRes.value.$el.querySelector('.el-scrollbar__wrap')
      if (container) {
        container.style.scrollBehavior = 'smooth'
        container.scrollTop = container.scrollHeight
      }
    }
  })
}

watch(
    () => props.messages,
    scrollToBottom,
    { immediate: true, deep: true }
)
</script>

<template>
  <el-container class="chat-container">
    <el-header class="chat-header">
      <h2>Vue WebSocket Chat Demo</h2>
    </el-header>

    <el-alert
        v-if="connecting"
        title="Connecting..."
        type="info"
        :closable="false"
        class="connecting-alert"
    />

    <el-main class="message-area">
      <el-scrollbar ref='scrollMenuRes' height="100%">
        <transition-group name="message">
          <div v-for="(message, index) in messages" :key="index" class="message-item" :class="message.type === 'CHAT' ? 'chat-message' : 'event-message'">
            <div v-if="message.type === 'CHAT'" class="chat-content">
              <el-avatar :size="32" :style="{ backgroundColor: message.color }" class="user-avatar">
                {{ message.sender[0] }}
              </el-avatar>
              <div class="message-block">
                <span class="sender-name">{{ message.sender }}</span>
                <div class="message-bubble">{{ message.content }}</div>
              </div>
            </div>
            <div v-else-if="message.type === 'JOIN'" class="event-content">
              <span class="event-text">{{ message.sender }} 进入了聊天</span>
            </div>
            <div v-else-if="message.type === 'LEAVE'" class="event-content">
              <span class="event-text">{{ message.sender }} 离开了聊天</span>
            </div>
            <div v-else-if="message.type === 'IMAGE'" class="chat-content">
              <el-avatar :size="32" :style="{ backgroundColor: message.color }" class="user-avatar">
                {{ message.sender[0] }}
              </el-avatar>
              <div class="message-block">
                <span class="sender-name">{{ message.sender }}</span>
                <div class="message-bubble">
                  <el-image :src="message.content"  fit="cover" class="chat-image"/>
                </div>
              </div>
            </div>
          </div>
        </transition-group>
      </el-scrollbar>
    </el-main>

    <el-footer class="input-footer">
      <el-form @submit.prevent="handleSubmit">
        <el-row :gutter="10">
          <el-col :span="3">
            <el-upload :action="uploadUrl" :show-file-list="false" :on-success="handleUploadSuccess" :on-error="handleUploadError" :with-credentials="true" accept="image/*">
              <el-button type="primary">
                Upload<el-icon class="el-icon--right"><Upload /></el-icon>
              </el-button>
            </el-upload>
          </el-col>
          <el-col :span="17">
            <el-input
                v-model="messageInput"
                placeholder="Type a message..."
                autocomplete="off"
                clearable
            />
          </el-col>
          <el-col :span="4">
            <el-button type="primary" native-type="submit" class="send-btn">Send</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-footer>

  </el-container>
</template>

<style scoped>
/* 图片样式 */
.chat-image {
  max-width: 200px;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.2s;
}

.chat-image:hover {
  transform: scale(1.02);
}

.chat-container {
  height: 100vh;
  max-width: 80%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.chat-header {
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.connecting-alert {
  margin: 0 20px;
}

.message-area {
  flex: 1;
  padding: 20px;
  overflow: hidden;
}

.message-item {
  margin-bottom: 16px;
  transition: all 0.3s;
}

.user-avatar {
  flex-shrink: 0;
  font-weight: bold;
}

.chat-content {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.message-block {
  display: flex;
  flex-direction: column;
  gap: 4px;
  max-width: 80%;
}

.sender-name {
  color: #409eff;
  font-weight: 500;
  font-size: 0.9em;
  padding-left: 4px;
}

.message-bubble {
  background-color: white;
  padding: 12px 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,.1);
  line-height: 1.5;
}

.event-content {
  text-align: center;
  padding: 8px 0;
}

.event-text {
  color: #909399;
  font-size: 0.9em;
}

.input-footer {
  padding: 20px;
  background-color: white;
  box-shadow: 0 -2px 12px 0 rgba(0,0,0,.1);
}

.send-btn {
  width: 100%;
}
</style>